<template>
  <el-row class="p-5 pt-0" @keyup.enter="getLoginLog">

    <el-col v-if="showSearch">
      <el-form ref="searchForm" :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="物理地址" class="font-black">
          <el-input v-model="search.loginLocation" :disabled="loading" :size="store.layoutSize" clearable
                    style="width: 180px"
                    placeholder="请输入物理地址"/>
        </el-form-item>
        <el-form-item label="用户名称" class="font-black">
          <el-input v-model="search.userName" :disabled="loading" :size="store.layoutSize" clearable
                    style="width: 180px"
                    placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="状态" class="font-black">
          <el-select v-model="search.status" :disabled="loading" :size="store.layoutSize" clearable style="width: 100px"
                     placeholder="状态" @change="getLoginLog">
            <el-option v-for="item in statusData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="登录时间" class="font-black">
          <el-date-picker
              style="width: 210px"
              v-model="date"
              type="daterange"
              unlink-panels
              range-separator="-"
              clearable
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
              :size="store.layoutSize"
              value-format="YYYY-MM-DD"
              @change="getLoginLog"
          />
        </el-form-item>
        <el-form-item>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space
                     type="primary"
                     @click="getLoginLog">
            <template #icon>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
            查询
          </el-button>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                     @click="clearSearch">
            <template #icon>
              <el-icon>
                <Refresh/>
              </el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col class="flex justify-between">
      <div>
        <el-button :disabled="search.total === 0 || loading" :size="store.layoutSize" auto-insert-space plain
                   type="warning"
                   @click="download">
          <template #icon>
            <el-icon>
              <Download/>
            </el-icon>
          </template>
          导出
        </el-button>
      </div>
      <div>
        <el-tooltip
            class="box-item"
            effect="dark"
            :content="showSearch?'隐藏搜索':'显示搜索'"
            placement="top"
        >
          <el-button :color="store.getTheme" :size="store.layoutSize" @click="showSearch = !showSearch"
                     circle>
            <el-icon #default>
              <Search/>
            </el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip
            class="box-item"
            effect="dark"
            content="刷新"
            placement="top"
        >
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" circle @click="getLoginLog">
            <el-icon #default>
              <Refresh/>
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </el-col>

    <el-col class="mt-2">
      <el-table :size="store.layoutSize" v-loading="loading" element-loading-text="正在努力加载中..."
                :data="tableLoginLog.data"
                style="width: 100%" table-layout="auto" row-key="id"
                highlight-current-row empty-text="无数据">

        <!--        <el-table-column align="center" reserve-selection="true" type="selection" width="55"/>-->

        <el-table-column align="center" label="访问编号" width="100" prop="infoId"/>

        <el-table-column align="center" label="用户名称" prop="userName"/>

        <el-table-column align="center" label="登录IP" prop="ipaddr" width="200"/>

        <el-table-column align="center" label="物理地址" prop="loginLocation"/>

        <el-table-column align="center" label="浏览器" prop="browser"/>

        <el-table-column align="center" label="操作系统" prop="os" width="140"/>

        <el-table-column align="center" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{
                scope.row.status === '0' ? '成功' : '失败'
              }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作信息" width="180" prop="msg"/>

        <el-table-column align="center" label="登录时间" width="180">
          <template #default="scope">
            {{ moment(scope.row.loginTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

      </el-table>
    </el-col>
    <el-col class="mt-3 flex justify-end">
      <el-pagination
          :small="store.layoutSize === 'small'"
          :default-current-page="search.pageNum"
          :currentPage="search.pageNum"
          :page-size='search.pageSize'
          :page-sizes="[10, 20, 50, 100]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="search.total"
          @size-change="handlePageSiezeChange"
          @current-change="handleCurrentPageChange"
      />
    </el-col>

  </el-row>
</template>

<script setup lang="ts">
import {useStore} from "@/store";
import {reactive, ref} from "vue";
import moment from "moment";
import {getDictData} from "@/api/dictData";
import {downloadLoginLogTable, getLoginLogTable} from "@/api/logininfor";
import {ElMessageBox} from "element-plus";

const store = useStore()

const loading = ref(false)

const showSearch = ref(true)

const date = ref([])

//赋值状态信息
const statusData = reactive({
  data: []
})
getDictData({'dictType': 'sys_common_status'}).then(result => {
  statusData.data = result.data.data
})

const search = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  userName: null,
  loginLocation: null,
  status: null,
  startDate: null,
  endDate: null
})

function clearSearch() {
  search.userName = null
  search.loginLocation = null
  search.status = null
  search.startDate = null
  search.endDate = null
  date.value = []
  getLoginLog()
}

const tableLoginLog = reactive({
  data: []
})
getLoginLog()

function getLoginLog() {
  loading.value = true
  if (date.value && date.value.length > 0) {
    search.startDate = date.value[0]
    search.endDate = date.value[1]
  } else {
    search.startDate = null
    search.endDate = null
  }
  getLoginLogTable(search).then(result => {
    search.total = result.data.data.total
    tableLoginLog.data = result.data.data.list
    loading.value = false
  })
}

//时间选择器快捷选择
const shortcuts = [
  {
    text: '上周内',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

//分页控制
function handleCurrentPageChange(val) {
  search.pageNum = val
  //获取数据
  getLoginLog()
}

//页大小控制
function handlePageSiezeChange(val) {
  search.pageSize = val
  //获取数据
  getLoginLog()
}

//导出数据
function download() {
  ElMessageBox.confirm('您确定要导出<' + search.total + '>条数据吗？', '警告', {
    confirmButtonText: '导出',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    downloadLoginLogTable(search).then(response => {
      let disposition = response.headers['content-disposition'];
      //以下部分有需要优化，如后端返回时没有携带文件后缀名,没有.时会有问题等等
      let filename = disposition ? disposition.substring(disposition.indexOf('=') + 1, disposition.indexOf('.')) : "下载文件";
      let newName = decodeURI(escape(filename))
      let extName = disposition.substring(disposition.indexOf('.') + 1)
      let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
      let link = document.createElement("a");
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", false, false);
      link.href = URL.createObjectURL(blob);
      link.download = newName + "." + extName;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(link.href);
    })
  })
}
</script>

<style scoped>

</style>
